package modules::fortune;

# alpha-0.03

use module;
use vars '@ISA';
@ISA = ("module");
use DBI;
use encoding "utf8";
use utf8;

sub got_groupchat_lorquotes {
my ($pkg,%args) = @_;
my (@words_vi) = split(/ /,$args{body}); # тело сообщения
# $args{from} - jid конференции
# $args{resource} - ник отправителя 
# $args{jid} - jid конференции
# $args{tag} - message
# $args{type} - groupchat
# $args{other} - HASH(0x8aa9470)

$words_vi[0] =~ tr/лбор/lbor/;
if ($words_vi[0] =~ /lor.*/) {
$fortunka = 'lor';
} elsif ($words_vi[0] =~ /bor.*/) {
$fortunka = 'bor';
}

$dbh = DBI->connect("DBI:mysql:$::db_anek:$::db_host:$::db_port", $::db_user, $::db_password);
#$dbh->do("SET character_set_results='utf8'");
$dbh->do("SET NAMES utf8");

$sql = "SELECT
        id,
        fort
        FROM
        $fortunka";
$sth = $dbh->prepare($sql);
$sth->execute();

$$fortunka = $sth->rows;

$sth->bind_columns(\$id, \$fort);
$randomf = int(rand($$fortunka));

$pizdohuj = ($words_vi[1] eq undef) ? "WHERE\nid='$randomf'" : "WHERE\nfort LIKE '\%$words_vi[1]\%'";
$sql = "SELECT
        id,
        fort
        FROM
        $fortunka
        $pizdohuj";
$sth = $dbh->prepare($sql);
$sth->execute();
$sth->bind_columns(\$id, \$fort);
if ($words_vi[1] eq undef) {
   $sth->fetch();
}else{
   while ($sth->fetch()) {
      push (@fortunki, $fort);
   }
$random_fort = int(rand($#fortunki));
$fort=$fortunki[$random_fort];
}
utf8::decode($fort);
unless ($fort) {
$fort = "Нихуя не найдено.";
}

main::SendMessage(to => $args{from}, type => $args{type}, body => "$fort");
$sth->finish;
$dbh->disconnect();
$#fortunki=0;
}


main::pd("................\n\n\n");
1;